package main

import (
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

// CORS 中间件
func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 设置 CORS 头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func main() {
	// HLS 输出目录
	outputDir := "./stream"

	// 确保输出目录存在
	if err := os.MkdirAll(outputDir, 0755); err != nil {
		log.Fatalf("Error creating output directory: %v", err)
	}

	// 创建一个新的 mux 来应用中间件
	mux := http.NewServeMux()

	// 设置路由
	mux.Handle("/stream/", http.StripPrefix("/stream/", http.FileServer(http.Dir(outputDir))))
	// 只提供 player.html
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" && r.URL.Path != "/index.html" {
			http.NotFound(w, r)
			return
		}
		//http.ServeFile(w, r, "player.html")
	})
	mux.HandleFunc("/rtsp", handleRTSPToFLV)
	mux.HandleFunc("/m3u8", func(w http.ResponseWriter, r *http.Request) {
		// TODO: 处理 m3u8 请求
		// ...
	})

	// 应用 CORS 中间件
	handler := corsMiddleware(mux)

	// 启动 HTTP 服务器
	go func() {
		log.Printf("Starting HTTP server on :8100")
		if err := http.ListenAndServe(":8100", handler); err != nil {
			log.Fatalf("HTTP server error: %v", err)
		}
	}()

	// 处理退出信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan
}
